package com.example.demo_text;

import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@WebServlet("/addCourse")
public class AddCourseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");

        String courseName = request.getParameter("courseName");

        // 验证输入
        if (courseName == null || courseName.trim().isEmpty()) {
            request.setAttribute("error", "课程名称不能为空！");
            request.getRequestDispatcher("add_course.jsp").forward(request, response);
            return;
        }

        // 检查课程名是否重复
        if (CourseDAO.isCourseNameExists(courseName)) {
            request.setAttribute("error", "该课程名称已存在，请更换其他名称");
            request.getRequestDispatcher("add_course.jsp").forward(request, response);
            return;
        }

        try {
            // 插入数据库（不传 course_id）
            int courseId = CourseDAO.addCourseAndGetId(courseName);

            if (courseId > 0) {
                // 添加成功，跳转至 class_space.jsp 并带参数
                response.sendRedirect("class_space.jsp?course_id=" + courseId);
            } else {
                request.setAttribute("error", "添加课程失败，请重试");
                request.getRequestDispatcher("add_course.jsp").forward(request, response);
            }

        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("error", "发生未知错误：" + e.getMessage());
            request.getRequestDispatcher("add_course.jsp").forward(request, response);
        }
    }
}
